<template>
  <div class="admin-dashboard">
    <!-- 平台概览区域 -->
    <div class="platform-overview">
      <div class="overview-content">
        <h1>洗护管理系统 - 管理员后台</h1>
        <p>今天是{{ currentDate }}，系统运行正常</p>
        <div class="admin-badge">
          <el-tag type="success" size="large">管理员专用系统</el-tag>
        </div>
      </div>
      <div class="quick-stats">
        <div class="stat-item">
          <span class="stat-number">{{ todayStats.newUsers || 0 }}</span>
          <span class="stat-label">今日新增用户</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ todayStats.newOrders || 0 }}</span>
          <span class="stat-label">今日新增订单</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">¥{{ todayStats.platformRevenue || 0 }}</span>
          <span class="stat-label">今日平台收入</span>
        </div>
      </div>
    </div>

    <!-- 核心数据卡片 -->
    <el-row :gutter="24" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card merchant-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ statistics.totalMerchants || 0 }}</h3>
              <p>入驻商家</p>
              <span class="trend up">+{{ statistics.merchantGrowth || 0 }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card user-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ statistics.totalUsers || 0 }}</h3>
              <p>注册用户</p>
              <span class="trend up">+{{ statistics.userGrowth || 0 }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card order-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ statistics.totalOrders || 0 }}</h3>
              <p>总订单数</p>
              <span class="trend up">+{{ statistics.orderGrowth || 0 }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card revenue-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <h3>¥{{ (statistics.totalRevenue || 0).toLocaleString() }}</h3>
              <p>平台总收入</p>
              <span class="trend up">+{{ statistics.revenueGrowth || 0 }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 管理操作区 -->
    <el-row :gutter="24" style="margin-top: 24px;">
      <el-col :span="16">
        <!-- 待审核商家 -->
        <el-card class="management-card">
          <template #header>
            <div class="card-header">
              <span>待审核商家</span>
              <el-button type="primary" @click="$router.push('/merchant/audit')">
                查看全部
              </el-button>
            </div>
          </template>
          <div v-loading="merchantsLoading">
            <el-table :data="pendingMerchants" style="width: 100%">
              <el-table-column prop="merchantName" label="商家名称" width="150" />
              <el-table-column prop="contactName" label="联系人" width="100" />
              <el-table-column prop="phone" label="联系电话" width="120" />
              <el-table-column prop="area" label="所在区域" width="100" />
              <el-table-column prop="submitTime" label="提交时间" width="140">
                <template #default="{ row }">
                  <span>{{ formatTime(row.submitTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="approveMerchant(row)">
                    通过
                  </el-button>
                  <el-button size="small" type="danger" @click="rejectMerchant(row)">
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="!pendingMerchants.length && !merchantsLoading" class="empty-data">
              <el-empty description="暂无待审核商家" />
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <!-- 快速管理 -->
        <el-card class="quick-actions-card">
          <template #header>
            <span>快速管理</span>
          </template>
          <div class="actions-grid">
            <div class="action-item" @click="$router.push('/merchant/list')">
              <el-icon><Shop /></el-icon>
              <span>商家管理</span>
            </div>
            <div class="action-item" @click="$router.push('/user/list')">
              <el-icon><UserFilled /></el-icon>
              <span>用户管理</span>
            </div>
            <div class="action-item" @click="$router.push('/order/list')">
              <el-icon><Document /></el-icon>
              <span>订单管理</span>
            </div>
            <div class="action-item" @click="$router.push('/statistics/overview')">
              <el-icon><TrendCharts /></el-icon>
              <span>数据统计</span>
            </div>
            <div class="action-item" @click="$router.push('/system/settings')">
              <el-icon><Setting /></el-icon>
              <span>系统设置</span>
            </div>
            <div class="action-item" @click="$router.push('/finance/settlement')">
              <el-icon><Money /></el-icon>
              <span>财务结算</span>
            </div>
          </div>
        </el-card>

        <!-- 平台状态 -->
        <el-card class="status-card" style="margin-top: 16px;">
          <template #header>
            <span>平台状态</span>
          </template>
          <div class="status-content" v-loading="statusLoading">
            <div class="status-item">
              <span>系统状态</span>
              <el-tag type="success">运行正常</el-tag>
            </div>
            <div class="status-item">
              <span>在线商家</span>
              <span>{{ platformStatus.onlineMerchants || 0 }}/{{ platformStatus.totalMerchants || 0 }}</span>
            </div>
            <div class="status-item">
              <span>活跃用户</span>
              <span>{{ platformStatus.activeUsers || 0 }}</span>
            </div>
            <div class="status-item">
              <span>处理中订单</span>
              <span>{{ platformStatus.processingOrders || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 异常告警 -->
    <el-row :gutter="24" style="margin-top: 24px;" v-if="alerts.length > 0">
      <el-col :span="24">
        <el-card class="alert-card">
          <template #header>
            <div class="card-header">
              <span>系统告警</span>
              <el-button type="text" @click="clearAlerts">清除所有</el-button>
            </div>
          </template>
          <div class="alerts-list">
            <el-alert
              v-for="alert in alerts"
              :key="alert.id"
              :title="alert.title"
              :description="alert.description"
              :type="alert.type"
              :closable="true"
              @close="removeAlert(alert.id)"
              style="margin-bottom: 12px;"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { Document, Money, User, Shop, UserFilled, TrendCharts, Setting } from '@element-plus/icons-vue'
import { statistics, order } from '@/api/wash/index'
import { getMerchants, approveMerchant, rejectMerchant } from '@/api/admin'
import { getAllLaundryOrders, approveMerchantApplication, rejectMerchantApplication } from '@/api/wash_service'

import {
  transformOrdersToStats,
  transformOrdersToTodayStats,
  transformOrdersToPendingMerchants,
  transformOrdersToPlatformStatus
} from '@/api/adapter'

export default {
  name: 'AdminDashboard',
  components: {
    Document, Money, User, Shop, UserFilled, TrendCharts, Setting
  },
  setup() {
    // 响应式数据
    const todayStats = reactive({
      newUsers: 0,
      newOrders: 0,
      platformRevenue: 0
    })

    const statistics = reactive({
      totalMerchants: 0,
      merchantGrowth: 0,
      totalUsers: 0,
      userGrowth: 0,
      totalOrders: 0,
      orderGrowth: 0,
      totalRevenue: 0,
      revenueGrowth: 0
    })

    const pendingMerchants = ref([])
    const platformStatus = reactive({
      onlineMerchants: 0,
      totalMerchants: 0,
      activeUsers: 0,
      processingOrders: 0
    })

    const alerts = ref([])

    // 加载状态
    const merchantsLoading = ref(false)
    const statusLoading = ref(false)

    const currentDate = computed(() => {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    })

    // 获取平台统计数据
    const loadPlatformStats = async () => {
      try {
        const response = await getAllLaundryOrders({ statistics: true })
        if (response && (response.code === 200 || response.data || response.content)) {
          const data = response.data || response
          const transformedStats = transformOrdersToStats(data)
          Object.assign(statistics, transformedStats)
        }
      } catch (error) {
        console.error('获取平台统计数据失败:', error)
        ElMessage.warning('获取平台数据失败，请检查网络连接')
      }
    }

    // 获取今日数据
    const loadTodayStats = async () => {
      try {
        const response = await getAllLaundryOrders({ period: 'today' })
        if (response && (response.code === 200 || response.data || response.content)) {
          const data = response.data || response
          const transformedStats = transformOrdersToTodayStats(data)
          Object.assign(todayStats, transformedStats)
        }
      } catch (error) {
        console.error('获取今日数据失败:', error)
      }
    }

    // 获取待审核商家
    const loadPendingMerchants = async () => {
      merchantsLoading.value = true
      try {
        const response = await getAllLaundryOrders({ status: 'PENDING' })
        if (response && (response.code === 200 || response.data || response.content)) {
          const data = response.data || response
          const transformedMerchants = transformOrdersToPendingMerchants(data)
          pendingMerchants.value = transformedMerchants
        }
      } catch (error) {
        console.error('获取待审核商家失败:', error)
        ElMessage.warning('获取商家数据失败，请检查网络连接')
        pendingMerchants.value = []
      } finally {
        merchantsLoading.value = false
      }
    }

    // 获取平台状态
    const loadPlatformStatus = async () => {
      statusLoading.value = true
      try {
        const response = await getAllLaundryOrders({ summary: true })
        if (response && (response.code === 200 || response.data || response.content)) {
          const data = response.data || response
          const transformedStatus = transformOrdersToPlatformStatus(data)
          Object.assign(platformStatus, transformedStatus)
        }
      } catch (error) {
        console.error('获取平台状态失败:', error)
      } finally {
        statusLoading.value = false
      }
    }

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return '-'
      return new Date(time).toLocaleDateString('zh-CN')
    }

    // 审核商家
    const approveMerchant = async (merchant) => {
      try {
        await ElMessageBox.confirm(
          `确定通过商家"${merchant.merchantName}"的申请吗？`,
          '审核确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await approveMerchantApplication(merchant.id)
        ElMessage.success('审核通过成功')
        await loadPendingMerchants()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审核商家失败:', error)
          ElMessage.error('审核失败，请稍后重试')
        }
      }
    }

    // 拒绝商家
    const rejectMerchant = async (merchant) => {
      try {
        const { value: reason } = await ElMessageBox.prompt(
          `请输入拒绝"${merchant.merchantName}"的原因：`,
          '审核拒绝',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputPlaceholder: '请输入拒绝原因...'
          }
        )
        
        await rejectMerchantApplication(merchant.id, { reason })
        ElMessage.success('已拒绝该商家申请')
        await loadPendingMerchants()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝商家失败:', error)
          ElMessage.error('操作失败，请稍后重试')
        }
      }
    }

    // 清除告警
    const clearAlerts = () => {
      alerts.value = []
      ElMessage.success('已清除所有告警')
    }

    // 移除单个告警
    const removeAlert = (alertId) => {
      const index = alerts.value.findIndex(alert => alert.id === alertId)
      if (index > -1) {
        alerts.value.splice(index, 1)
      }
    }

    // 加载所有数据
    const loadDashboardData = async () => {
      const loading = ElLoading.service({
        lock: true,
        text: '加载平台数据中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        await Promise.all([
          loadPlatformStats(),
          loadTodayStats(),
          loadPendingMerchants(),
          loadPlatformStatus()
        ])
      } catch (error) {
        console.error('加载仪表盘数据失败:', error)
        ElMessage.error('加载数据失败，请刷新页面重试')
      } finally {
        loading.close()
      }
    }

    onMounted(() => {
      loadDashboardData()
      
      // 设置定时刷新
      const refreshInterval = setInterval(() => {
        loadTodayStats()
        loadPendingMerchants()
        loadPlatformStatus()
      }, 30000) // 每30秒刷新一次

      // 组件卸载时清理定时器
      return () => {
        clearInterval(refreshInterval)
      }
    })

    return {
      currentDate,
      todayStats,
      statistics,
      pendingMerchants,
      platformStatus,
      alerts,
      merchantsLoading,
      statusLoading,
      formatTime,
      approveMerchant,
      rejectMerchant,
      clearAlerts,
      removeAlert,
      loadDashboardData
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.platform-overview {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-content h1 {
  font-size: 28px;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.overview-content p {
  margin: 0;
  opacity: 0.9;
  font-size: 16px;
}

.quick-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.merchant-card .card-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-card .card-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.order-card .card-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.revenue-card .card-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info h3 {
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 4px 0;
  color: #333;
}

.card-info p {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.trend {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
}

.trend.up {
  background: #f0f9ff;
  color: #1976d2;
}

.management-card, .quick-actions-card, .status-card, .alert-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.action-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
  transform: translateY(-2px);
}

.action-item .el-icon {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 8px;
}

.action-item span {
  font-size: 14px;
  color: #333;
}

.status-content {
  padding: 8px 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-item span:first-child {
  color: #666;
  font-size: 14px;
}

.status-item span:last-child {
  font-weight: 500;
  color: #333;
}

.empty-data {
  text-align: center;
  padding: 40px;
}

.alerts-list {
  max-height: 300px;
  overflow-y: auto;
}
</style> 